﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BoneImp {
	public class Bone {
		/* Data */
		public BoneData data;
		Bone parent;
		public float x, y;
		public float rotation;
		public float scaleX, scaleY;

		public float m00, m01, worldX; /* a b x */
		public float m10, m11, worldY; /* c d y */
		float worldRotation;
		float worldScaleX, worldScaleY;


		static bool yDown;

		/* Code */
		public static void setYDown(bool value) {
			yDown = value;
		}

		/* @param parent May be 0. */
		public Bone(BoneData data, Bone parent = null) {
			this.data = data;
			this.parent = parent;
			setToBindPose();
		}

		public void setToBindPose() {
			this.x = this.data.x;
			this.y = this.data.y;
			this.rotation = this.data.rotation;
			this.scaleX = this.data.scaleX;
			this.scaleY = this.data.scaleY;
		}

		public void updateWorldTransform (bool flipX, bool flipY) {
			if (this.parent != null) {
				this.worldX = this.x * this.parent.m00 + this.y * this.parent.m01 + this.parent.worldX;
				this.worldY = this.x * this.parent.m10 + this.y * this.parent.m11 + this.parent.worldY;
				this.worldScaleX = this.parent.worldScaleX * this.scaleX;
				this.worldScaleY = this.parent.worldScaleY * this.scaleY;
				this.worldRotation = this.parent.worldRotation + this.rotation;
			} else {
				this.worldX = this.x;
				this.worldY = this.y;
				this.worldScaleX = this.scaleX;
				this.worldScaleY = this.scaleY;
				this.worldRotation = this.rotation;
			}
			float radians = (float)(this.worldRotation * 3.1415926535897932385 / 180);
			float cosine = (float)Math.Cos(radians);
			float sine = (float)Math.Sin(radians);
			this.m00 = cosine * this.worldScaleX;
			this.m10 = sine * this.worldScaleX;
			this.m01 = -sine * this.worldScaleY;
			this.m11 = cosine * this.worldScaleY;
			if (flipX) {
				this.m00 = -this.m00;
				this.m01 = -this.m01;
			}
			if (flipY) {
				this.m10 = -this.m10;
				this.m11 = -this.m11;
			}
			if (yDown) {
				this.m10 = -this.m10;
				this.m11 = -this.m11;
			}
		}
	}
}
